package cn.fjc920.siaa.activitys

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.content.edit
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activityutils.BaseActivity
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import cn.fjc920.siaa.internetUtils.OkhttpUtils.DataCallBack
import cn.fjc920.siaa.internetUtils.LoadingDialog
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException

open class LoginActivity : BaseActivity() {

    private lateinit var userName:String
    private lateinit var password:String
    private lateinit var url:String
    private lateinit var map:HashMap<String,String>
    private lateinit var context: Context
    protected lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        init()
        initClick()
    }

    private fun init(){
        if (isDarkTheme(this)){
            img_logo2.setImageResource(R.mipmap.siaa_logo_bai)
        }

        context = this
        url = "${OkhttpUtils.url}login"
    }
    
    private fun initClick(){
        btn_login.setOnClickListener {
            userName = et_userName.text.toString()
            password = et_password.text.toString()

            if (userName.isNotEmpty() && password.isNotEmpty()) {

                OkhttpUtils.getAsync(url, object : DataCallBack {
                    override fun requestFailure(request: Request?, e: IOException?) {

                    }

                    override fun requestSuccess(result: String?) {

                        //获取_csrf
                        val doc = Jsoup.parse(result!!)
                        val input = doc.select("input[type=hidden]")
                        val element = input[0]
                        val _csrf = element.attr("value")
                        map = HashMap()
                        map["username"] = userName
                        map["password"] = password
                        map["_csrf"] = _csrf
                        map["remember-me"] = "on"

                        OkhttpUtils.postAsync(url, map, object : OkhttpUtils.DataCallBack {
                            val loadingDialog = LoadingDialog(context).apply {
                                show("登陆中")
                            }

                            override fun requestFailure(request: Request?, e: IOException?) {
                                loadingDialog.dismiss()
                                Toast.makeText(context, "登录失败，请检查网络", Toast.LENGTH_SHORT).show()
                            }

                            override fun requestSuccess(result: String) {

                                if (result.contains(userName)) {
                                    initFast()
                                    HomePageActivity.actionStart(context)
                                    getSharedPreferences("userData", Context.MODE_PRIVATE).edit {
                                        putString("userName", userName)
                                        putString("password", password)
                                    }
                                    finish()
                                } else {
                                    loadingDialog.dismiss()
                                    Toast.makeText(context, "用户名或密码不正确", Toast.LENGTH_SHORT).show()
                                    OkhttpUtils.cookieStore.clear()
                                }
                            }
                        })
                    }
                })
            }else{
                Toast.makeText(context, "请检查用户名或密码是否为空！", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun initFast(){
        //动态方式添加一
        val shortScan = ShortcutInfoCompat.Builder(this, "add")//唯一标识id
            .setShortLabel(getString(R.string.add))//短标签
            .setIcon(IconCompat.createWithResource(this, R.drawable.ic_add_hours))//图标
            //跳转的目标，定义Activity
            .setIntent(Intent(Intent.ACTION_MAIN, null, this, FastAddActivity::class.java))
            .build()
        //执行添加操作
        ShortcutManagerCompat.addDynamicShortcuts(this, mutableListOf(shortScan))
    }

    companion object{
        fun actionStart(context: Context){
            val intent = Intent(context, LoginActivity::class.java)
            context.startActivity(intent)
        }
    }
}